<?php

namespace App\Jobs;

use App\Models\Order;
use Illuminate\Support\Facades\DB;

class GoodsOrderCancelJob extends Job
{
    protected $job_name ='GoodsOrderCancelJob';
    private $runtime = null;
    private $rows_per_loop =10;

    /**
     * 创建一个新的任务实例。
     *
     * @param $time 启动时间
     */
    public function __construct($time)
    {
        parent::__construct();
        $this->runtime = $time;
    }

    /**
     * 运行任务。
     *
     * @return void
     */
    public function handle()
    {
        //业务说明:定时清理未支付订单

        $this->logger->info('========start======');
        $this->logger->info('runtime:'.$this->runtime);

        $time = DB::table('config')->where('code','order_info_live_time_goods')->value('value');//自动取消时间 （分钟）

        $timeline = $this->runtime;

        //商品订单
        $this->cancelGoodsOrder($time,$timeline);

        $this->logger->info('========end======');
    }

    private function cancelGoodsOrder($time=30,$timeline){

        $this->logger->info('========取消未付款商品订单======');

        $i =1;//批次
        $orders =null;

        while(true){

            $this->logger->info('【第'.$i.'批】');
            /* 默认30分钟 */
            $cancel_time = $time*60;
            /* 超时未付款的订单 */
            $orders = Order::where('delflg_buyer','=',0)
                ->where('delflg_seller','=',0)
                ->where('status','=',ORDER_PENDING)
                ->where('add_time','<',$timeline - $cancel_time)
                ->select('order_id')
                ->skip(0)->take($this->rows_per_loop)
                ->get();

            $this->logger->info('总数:'.count($orders));

            if(count($orders)==0){
                break;
            }

            $order_ids =array_pluck($orders,'order_id');

            $this->logger->info('执行: '.json_encode($order_ids));

            $order_pending = '待付款'; //待支付
            $order_canceld= '已取消'; //已取消

            DB::beginTransaction();

            try{

                /* 更新订单状态 */
                DB::table('order')
                    ->whereIn('order_id',$order_ids)
                    ->update([
                        'status' => ORDER_CANCELED,
                    ]);

                /* 操作记录 */
                foreach ($order_ids as $order_id)
                {
                    $order_logs[] = array(
                        'order_id'  => $order_id,
                        'operator'  => '0',
                        'order_status' => $order_pending,
                        'changed_status' => $order_canceld,
                        'remark'    => '系统取消过期未支付订单',
                        'log_time'  => $timeline,
                    );
                }

                foreach($order_logs as $orderlog){
                    DB::table('order_log')->insert($orderlog);
                }

                DB::commit();

            } catch(\Exception $e){
                DB::rollback();
                $this->logger->info('error msg:'. $e->getMessage() . ' trace:'. $e->getTraceAsString());
            }

            if(count($orders)<$this->rows_per_loop){
                break;
            }

            $i++;

        }

    }

}
